'use strict';

const {
	XMLParser
} = require("fast-xml-parser");
const {
	mainSpaceId
} = require('config-main-space')
const db = uniCloud.database();
const wmzAdvertiserSdk = uniCloud.importObject('wmz-advertiser-sdk')
exports.main = async (event, context) => {
	let response = {
		mpserverscssComposedResponse: true,
		statusCode: 200
	};
	let data = event.body;
	if (event.isBase64Encoded) {
		data = new Buffer(data, 'base64').toString();
	}

	let res = {};
	let payObj = {};

	const path = event.path;
	switch (path) {
		case '/alipay':

			payObj.name = '支付宝支付';
			payObj.way = 'alipay';

			let queryArr = data.split("&");
			queryArr.forEach(function(item) {
				let key = item.split("=")[0];
				res[key] = item.split("=")[1];
			});
			res.total_fee = res.total_amount * 100;
			res.transaction_id = res.trade_no;

			break;
		case '/wechat':

			payObj.name = '微信支付';
			payObj.way = 'wechat';

			const parser = new XMLParser();
			res = parser.parse(data);
			res = res.xml;

			try {
				//特殊处理transaction_id
				let transaction_ids = data.split('<transaction_id><![CDATA[');
				if (transaction_ids.length > 0) {
					res.transaction_id = transaction_ids[1].split("]]></transaction_id>")[0];
				}
			} catch (e) {
				uniCloud.logger.info("微信支付支付通知异常: ", JSON.stringify(e));
			}

			break;
		default:

			uniCloud.logger.info(`支付通知标识不正确`);
			return response;
	}
	if (res && ((res.return_code && 'SUCCESS' === res.return_code) || (res.trade_status && 'TRADE_SUCCESS' ===
			res.trade_status))) {
		let outTradeNo = res.out_trade_no ? res.out_trade_no : null;
		let transactionId = res.transaction_id ? res.transaction_id : null;
		let alipayVouchers = res.alipay_vouchers ? res.alipay_vouchers : null;

		if (!outTradeNo) {
			uniCloud.logger.info(`outTradeNo参数丢失`);
			return response;
		}

		let entitlementOrder = await db.collection('wmz-entitlement-order').doc(outTradeNo).get()
		entitlementOrder = entitlementOrder.data[0]
		if (entitlementOrder) {
			if (entitlementOrder.status === '待付款') {
				await db.collection('wmz-entitlement-order').doc(outTradeNo).update({
					status: '已付款',
					pay_time: new Date().getTime(),
					trade_no: transactionId
				})
				let coupon_data = entitlementOrder.coupon_data
				for (var i in coupon_data) {
					coupon_data[i].entitlement_id = entitlementOrder.entitlement_id
					coupon_data[i].goods_type = entitlementOrder.goods_type
					coupon_data[i].order_id = entitlementOrder._id
					coupon_data[i].user_id = entitlementOrder.user_id
					coupon_data[i].ali_user_id = entitlementOrder.ali_user_id
					coupon_data[i].status = '未使用'
					coupon_data[i].app_id = entitlementOrder.app_id
					coupon_data[i].create_time = new Date().getTime()
					let cRes = await db.collection('wmz-entitlement-coupon').add(coupon_data[i])
					/* if (cRes.id) {
						if (entitlementOrder.goods_type) {
							let type
							if (entitlementOrder.goods_type === 'mobile_coupon') {
								type = 'mobile_recharge'
							}
							if (type) {
								let goodsData = await this.db.collection('wmzmall-goods').where({
									app_id: entitlementOrder.app_id,
									type: type
								}).get()
								goodsData = goodsData.data
								if (goodsData.length > 0) {
									goodsData = goodsData[0]
									await db.collection('wmzmall-marketing-coupon').add({
										_id: cRes.id,
										is_delete: 0,
										state: '已领取',
										member_id: entitlementOrder.user_id,
										"end_time": 1919687379000,
										"allow_type": "goods",
										"type": "满减",
										price: coupon_data[i].money * 100,
										"allow_jsons": [{
											"_id": goodsData._id
										}]
									})
								}
							}
						}

					} */
				}
				let appId = entitlementOrder.app_id;
				let shopId = entitlementOrder.shop_id;
				let title = '收款';
				let cate = '权益卡购买';
				let type = 0;
				let orderNo = transactionId;
				let way = "支付宝";
				let payMoney = entitlementOrder.money * 100;

				if (way.indexOf('支付宝') > -1) {
					way = '支付宝支付';
				}
				let shopie = {
					app_id: appId,
					shop_id: shopId,
					order_no: orderNo,
					title: title,
					cate: cate,
					type: type,
					way: way,
					money: payMoney,
					create_time: new Date().getTime()
				};
				let addShopieResult = await db.collection('wmzmall-shopie').add(shopie);

				if (entitlementOrder.goods_type) {

				} else {
					if (entitlementOrder.channel) {
						let url = 'http://47.109.42.104/api/order/miniprog/callback?orderId=' + entitlementOrder
							.orderId + '&phone=' + entitlementOrder.phone + '&finger=' + entitlementOrder
							.finger +
							'&channel=' + entitlementOrder.channel
						let rres = await uniCloud.httpclient.request(url, {
							method: 'POST',
							headers: {
								"Content-Type": "x-www-form-urlencoded"
							}, // 请求头
							dataType: 'json' // 此处指定为json表示将此请求的返回值解析为json
						})
						uniCloud.logger.info(url)
						uniCloud.logger.info(rres)
					} else {
						let advertisers = await db.collection('wmz-advertiser').where({
							app_id: appId,
							count_status: 0
						}).get()
						advertisers = advertisers.data

						let entitlementData = await db.collection('wmz-entitlement').doc(entitlementOrder
							.entitlement_id).get()
						entitlementData = entitlementData.data[0]
						let callback_count = ""
						if (entitlementData) {
							callback_count = entitlementData.callback_count + ""
						}
						let tCount = advertisers.length
						if (callback_count.indexOf(tCount) > -1 && tCount < 11) {
							if (entitlementOrder.finger.indexOf('userkey') > -1) {
								let plid = 0
								if (entitlementOrder.finger.indexOf('plid') > -1) {
									plid = entitlementOrder.finger.split('plid')[1]
									plid = plid.split('plid,')[0]
								}
								let url = 'https://game.adtianshi.cn/UrlCenter/Transfer?plid=' + plid
								let userkey = ""
								if (entitlementOrder.finger.indexOf('userkey') > -1) {
									userkey = entitlementOrder.finger.split('userkey')[1]
									userkey = userkey.split('userkey,')[0]
									url += "&userkey=" + userkey
								}
								url += "&type=" + 2
								let adtianshiRes = await uniCloud.httpclient.request(url, {
									method: 'GET',
									dataType: 'json' // 此处指定为json表示将此请求的返回值解析为json
								})
								await db.collection('wmz-advertiser').add({
									phone: entitlementOrder.phone,
									price: entitlementOrder.money,
									app_id: appId,
									shop_id: shopId,
									status: 1,
									count_status: 0,
									entitlement_id: entitlementOrder.entitlement_id,
									create_time: new Date().getTime(),
									"url": url,
									"res": adtianshiRes
								})
							} else if (entitlementOrder.finger.indexOf('landingid') > -1) {
								let landingid = entitlementOrder.finger.split('landingid')[1]
								let url = 'https://oicount.adexplain.com/v2/action/monitor?landingid=' +
									landingid
								url += "&exposure=" + 0
								let landingidRes = await uniCloud.httpclient.request(url, {
									method: 'GET',
									dataType: 'json' // 此处指定为json表示将此请求的返回值解析为json
								})

								await db.collection('wmz-advertiser').add({
									phone: entitlementOrder.phone,
									price: entitlementOrder.money,
									app_id: appId,
									shop_id: shopId,
									status: 1,
									count_status: 0,
									entitlement_id: entitlementOrder.entitlement_id,
									"url": url,
									"res": landingidRes
								})
							} else {
								let wmzAdvertiserRes = await wmzAdvertiserSdk.callback({
									orderNo: entitlementOrder.finger,
									phone: entitlementOrder.phone,
									price: entitlementOrder.money
								})
								if (wmzAdvertiserRes.data.code === 200) {
									await db.collection('wmz-advertiser').add({
										order_no: entitlementOrder.finger,
										phone: entitlementOrder.phone,
										price: entitlementOrder.money,
										app_id: appId,
										shop_id: shopId,
										status: 1,
										entitlement_id: entitlementOrder.entitlement_id,
										count_status: 0,
										create_time: new Date().getTime()
									})
								}
							}
							await db.collection('wmz-entitlement-order').doc(outTradeNo).update({
								callback_status: true
							})
						} else {
							if (tCount >= 10) {
								await db.collection('wmz-advertiser').where({
									app_id: appId,
									count_status: 0
								}).update({
									count_status: 1
								})
							}
							await db.collection('wmz-advertiser').add({
								order_no: entitlementOrder.finger,
								phone: entitlementOrder.phone,
								price: entitlementOrder.money,
								app_id: appId,
								shop_id: shopId,
								entitlement_id: entitlementOrder.entitlement_id,
								status: 2,
								count_status: 0,
								create_time: new Date().getTime()
							})
						}
					}
				}

				let tdb = uniCloud.database({
					provider: 'tencent',
					spaceId: mainSpaceId
				})
				await tdb.collection('wmzmall-shopie').add(shopie)
				let appletInfoData = await db.collection('wmz-applet-info').doc(appId).get()
				appletInfoData = appletInfoData.data[0]
				const smsRes = await uniCloud.sendSms({
					appid: '__UNI__DA2AF40',
					smsKey: "1d987a96a3dc152c55120e6382f6e7f1",
					smsSecret: "9b3ff3f85da19e9a6302d38c6c1266c4",
					phone: entitlementOrder.phone,
					templateId: '30429', // 请替换为自己申请的模板id
					data: {
						name: appletInfoData.alipay.recharge_wechat_name,
						aname: appletInfoData.alipay.recharge_applet_name,
						mobile: appletInfoData.phone
					}
				})
				console.log(smsRes)
			}
		}

	}
}